const initialState = {
  comments: {
    total_count: 0,
    end_id: '',
    last_id: '',
    results: [] as CommentsType[],
  },

  // 原始评论
  originComment: {} as CommentsType,

  // 回复评论列表
  replyComments: {
    end_id: '',
    last_id: '',
    results: [] as CommentsType[],
  },
};

export default function commentsReducer(
  state = initialState,
  action: CommentsActionType
): typeof initialState {
  switch (action.type) {
    case 'comments/saveComments':
      return {
        ...state,
        comments: action.payload,
      };
    case 'comments/clearComments':
      return {
        ...state,
        comments: {} as any,
      };

    // 保存原始评论
    case 'comments/saveOriginComment':
      return {
        ...state,
        originComment: action.payload,
      };
    // 清除原始评论
    case 'comments/clearOriginComment':
      return {
        ...state,
        originComment: {} as CommentsType,
      };

    case 'comments/saveReplyComments':
      return {
        ...state,
        replyComments: action.payload,
      };
    // 清除回复评论列表
    case 'comments/clearReplyComments':
      return {
        ...state,
        replyComments: { results: [] } as any,
      };
    // 更新回复评论数
    case 'comments/updateReplyCommentCount':
      return {
        ...state,
        originComment: {
          ...state.originComment,
          reply_count: action.payload,
        },
      };
    default:
      return state;
  }
}

export type CommentsType = {
  com_id: string;
  content: string;
  reply_count: number;
  pubdate: string;
  is_followed: boolean;
  is_liking: boolean;
  like_count: number;
  aut_id: string;
  aut_name: string;
  aut_photo: string;
};

export type CommentsActionType =
  | { type: 'comments/saveComments'; payload: typeof initialState.comments }
  | { type: 'comments/clearComments' }
  // 保存原始评论
  | { type: 'comments/saveOriginComment'; payload: CommentsType }
  | { type: 'comments/clearOriginComment' }
  //
  | {
      type: 'comments/saveReplyComments';
      payload: typeof initialState.replyComments;
    }
  | { type: 'comments/clearReplyComments' }
  // 更新回复评论数
  | { type: 'comments/updateReplyCommentCount'; payload: number };
